#include "sqlite.hpp"
#include <cassert>
#include <vector>

struct User
{
    int id;
    std::string name;
    int age;
};

// 查询回调函数，将查询到的结果保存到vector中
int selectCallback(void* data, int col_count, char** result, char** fields_name)
{
    std::vector<User>* users_ptr = reinterpret_cast<std::vector<User>*>(data);
    if(col_count == 3)
        users_ptr->push_back({atoi(result[0]), result[1], atoi(result[2])});
    return 0;
}

void print(const std::vector<User>& users)
{
    for(auto& user : users)
        std::cout << "id: " << user.id << ", name: " << user.name << ", age: " << user.age << std::endl;
}

int main()
{
    // 1. 打开数据库文件
    SqliteDB sqlite_db("test.db");
    assert(sqlite_db.open());

    // 2. 创建表
    std::string create_sql = "create table if not exists user(id integer primary key autoincrement, name varchar(20), age int)";
    sqlite_db.execute(create_sql, nullptr, nullptr);

    // 3. 数据的增删改查
    // 3.1 插入数据
    std::string insert_sql = "insert into user(name, age) values('张三', 18), ('李四', 19), ('王五', 20), ('赵六', 21)";
    sqlite_db.execute(insert_sql, nullptr, nullptr);

    // 3.2 修改
    std::string update_sqlite = "update user set age = 19 where name = '张三'";
    sqlite_db.execute(update_sqlite, nullptr, nullptr);

    // 3.3 删除
    std::string delete_sql = "delete from user where age = '20'";
    sqlite_db.execute(delete_sql, nullptr, nullptr);

    // 3.4 查询
    std::string select_sql = "select id, name, age from user";
    std::vector<User> users;
    sqlite_db.execute(select_sql, selectCallback, &users);
    print(users);

    // 4. 关闭数据库
    sqlite_db.close();
    
    return 0;
}